<template>
  <el-card style="height: 80px">
    <el-form :inline="true" class="form">
      <el-form-item label="用户名：">
        <el-input
          placeholder="请输入搜索用户名"
          size="normal"
          clearable
          @change=""
          v-model="keyword"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="default" @click="search" :disabled="keyword?false:true">搜索</el-button>
        <el-button type="primary" size="default" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0px">
    <el-button type="primary" size="default" @click="addUser">添加用户</el-button>
    <el-button type="primary" size="default" @click="deleteSelectUser" :disabled="seleteIdArr.length?false:true">批量删除</el-button>
    <!-- 展示用户信息 -->
    <el-table style="margin: 10px 0px" border :data="UserListData" @selection-change="seleteChange">
      <el-table-column type="selection"></el-table-column>
      <el-table-column type="index" label="#" align="center" ></el-table-column>
      <el-table-column label="id" align="center" prop="id" width="110px"></el-table-column>
      <el-table-column label="用户名" align="center" prop="username" width="110px"></el-table-column>
      <el-table-column label="用户名称" align="center" prop="name" width="110px"></el-table-column>
      <el-table-column label="用户角色" align="center" prop="roleName" width="100px"></el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="操作" width="280px" align="center">
        <template #="{ row}">
          <el-button type="primary" size="small" @click="setRole(row)" icon="UserFilled"
            >分配角色</el-button
          >
          <el-button type="primary" size="small" @click="updateUser(row)" icon="edit"
            >编辑</el-button
          >
          <el-popconfirm :title="`你去确定删除${row.username}?`" width="260px" @confirm="deleteUser(row.id)">
            <template #reference>
              <el-button type="primary" size="small" @click="" icon="delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize4"
      :page-sizes="[5, 7, 9, 11]"
      :background="true"
      layout="prev, pager, next, jumper,->,sizes,total,"
      :total="total"
      @current-change="CurrentChange"
      @size-change="SizeChange"
    />
  </el-card>
  <!-- 抽屉效果 -->
  <el-drawer v-model="drawer">
    <!-- 头部标题 -->
    <template #header>
      <h4>{{ UserParams.id ? "修改用户" : "添加用户" }}</h4>
    </template>
    <template #default>
      <el-form :model="UserParams" :rules="rules" ref="formRef">
        <el-form-item label="用户姓名" prop="username">
          <el-input
            placeholder="请输入用户姓名"
            size="normal"
            clearable
            @change=""
            v-model="UserParams.username"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="name">
          <el-input
            placeholder="请输入用户昵称"
            size="normal"
            clearable
            @change=""
            v-model="UserParams.name"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="!UserParams.id">
          <el-input
            placeholder="请输入用户密码"
            size="normal"
            clearable
            @change=""
            v-model="UserParams.password"
          ></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </template>
  </el-drawer>
  <!-- 用于某一个已有帐号 -->
  <el-drawer v-model="drawer1" >
    <template #header>
      <h4>分配角色</h4>
    </template>
    <template #default>
      <el-form>
        <el-form-item label="用户姓名">
          <el-input
            v-model="UserParams.username"
            placeholder=""
            size="normal"
            clearable
            @change=""
            :disabled="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色列表">
            <!-- 显示职位复选框 
               v-model:是否全选控制
               :indeterminate="isIndeterminate":设置不确定样式
               @change="handleCheckAllChange":全选复选框发生变化触发
               -->
          <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
          <!-- v-model="userRole":收集数据
                :label="role"：收集所选的值
                @change="handleCheckedCitiesChange":复选框change事件-->
          <el-checkbox-group v-model="userRole" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="(role,_index) in allRole" :key="role.id" :label="role" >
              {{ role.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawer1 = false">取消</el-button>
        <el-button type="primary" @click="confirmClick">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { reqAddAndUpdataUser, reqDeleteAllUser, reqDeleteUser, reqGetUserList, reqSetUserRole, reqUserRole } from "@/api/acl/user";
import { SetUserRole, UserData, UserDateList, UserRole } from "@/api/acl/user/type";
import useLayOutSettingStore from '@/store/modules/setting'
import { ElMessage } from "element-plus";
import { ref, onMounted, reactive, nextTick } from "vue";
//页码设置
let pageNo = ref<number>(1);
//一页展示多少条数据
let pageSize4 = ref<number>(5);
let UserListData = ref<UserData[]>([]);
//获取总数数据
let total = ref<number | string>("");
//控制抽屉显示与隐藏
let drawer = ref<boolean>(false);
//收集用户信息
let UserParams = reactive<UserData>({
  id: "",
  createTime: "",
  updateTime: "",
  username: "",
  password: "",
  name: "",
  phone: "",
  roleName: "",
});
//获取form组件实例
let formRef = ref<any>();
//控制分配角色
let drawer1 = ref<boolean>(false);

//控制多选框是否全选
let checkAll = ref<any>(false)
//设置多选框不确定样式
let isIndeterminate = ref<boolean>(false)
let allRole = ref<UserRole[]>([])
//多选款收集到的组件
let userRole = ref<UserRole[]>([])
onMounted(() => {
  getUserDataist();
});
//准备一个数组批量删除用户id
let seleteIdArr = ref<UserData[]>([])
//定义响应式数据
let keyword = ref<string>('')
//获取模板仓库
let settingStore = useLayOutSettingStore();
const getUserDataist = async () => {
  let result: UserDateList = await reqGetUserList(pageNo.value, pageSize4.value,keyword.value);
  if (result.code == 200) {
    UserListData.value = result.data.records;
    total.value = result.data.total;
  }
};
const CurrentChange = () => {
  getUserDataist();
};
const SizeChange = () => {
  getUserDataist();
};
//添加
const addUser = () => {
  drawer.value = true;
  Object.assign(UserParams, {
    id: "",
    createTime: "",
    updateTime: "",
    username: "",
    password: "",
    name: "",
    phone: "",
    roleName: "",
  });
  //当第一次点击时，dom还未过载,所以无法获取DOM,用nextTick()DOM挂载完毕后执行
  nextTick(() => {
    formRef.value.clearValidate("username");
    formRef.value.clearValidate("name");
    formRef.value.clearValidate("password");
  });
};
//编辑
const updateUser = (row: UserData) => {
  drawer.value = true;
  //存储收集数据信息
  Object.assign(UserParams, row);
  //清除上一次验证信息
  nextTick(() => {
    formRef.value.clearValidate("username");
    formRef.value.clearValidate("name");
  });
};
//保存按纽回调
const save = async () => {
  //保存按钮：添加/修改
  //点击保存按钮群不符合条件才会发请求
  await formRef.value.validate();
  let result: any = await reqAddAndUpdataUser(UserParams);
  if (result.code == 200) {
    drawer.value = false;
    ElMessage({
      type: "success",
      message: UserParams.id ? "更新用户成功" : "添加用户成功",
    });
    getUserDataist();
    //浏览器自动刷新一次
    window.location.reload();
  } else {
    drawer.value = false;
    ElMessage({
      type: "success",
      message: UserParams.id ? "更新用户失败" : "添加用户失败",
    });
  }
};
const cancel = () => {
  drawer.value = false;
};
//校验用户名回调
const validatorUserName = (_rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 5) {
    callBack();
  } else {
    callBack(new Error("用户名长度至少5位"));
  }
};
const validatorname = (_rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 5) {
    callBack();
  } else {
    callBack(new Error("用户昵称长度至少5位"));
  }
};
const validatorpassword = (_rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 5) {
    callBack();
  } else {
    callBack(new Error("密码长度至少5位"));
  }
};
//表单校验规则
const rules = {
  name: [{ required: true, trigger: "blur", validator: validatorUserName }],
  username: [{ required: true, trigger: "blur", validator: validatorname }],
  password: [{ required: true, trigger: "blur", validator: validatorpassword }],
};
//分配角色按钮回调
const setRole = async(row: UserData) => {
  let result = await reqUserRole(row.id as number)
  allRole.value = result.data.allRolesList
  userRole.value = result.data.assignRoles
  drawer1.value = true;
  //存储已有用户信息
  Object.assign(UserParams, row);

};
//全选选框发生变化时触发
const handleCheckAllChange = (val:boolean)=>{
  //val:代表是否处于全选(true)/全不选(false)
  //全选：当val=true时将数据赋值给userRole || 将不确定状态变为false
  //全部选：将空[]赋值给userRole
  userRole.value = val?allRole.value:[]
  //不确定样式
  isIndeterminate.value = false
}
//复选框发生变化时触发
const handleCheckedCitiesChange = (value:string[])=>{
  //判断数据数组与选择数组是否相等
  //value:返回选中的数组
  checkAll.value = value.length === allRole.value.length
   //顶部的复选框不确定的样式
  isIndeterminate.value = value.length !== allRole.value.length
}
//分配角色回调
const confirmClick = async()=>{
  //收集参数
  let data:SetUserRole = {
    userId:UserParams.id,
    roleIdList:userRole.value.map(item=>{
      return item.id as number
    })
  }
 let result =  await reqSetUserRole(data)
 if(result.code==200){
  ElMessage({
    type:'success',
    message:'分配成功'
  })
  getUserDataist()
  drawer1.value = false
 }else{
  ElMessage({
    type:'error',
    message:'分配职位失败'
  })
  getUserDataist()
  drawer1.value = false
 }
}
const deleteUser = async(id:number)=>{
  let result:any =  await reqDeleteUser(id)
  if(result.code==200){
   ElMessage({
    type:'success',
    message:'删除成功'
   })
   getUserDataist()  
  }else{
    ElMessage({
    type:'error',
    message:'删除失败'
   })
  }
}
//复选框勾选触发事件
const seleteChange=(value:any)=>{
  //勾选事件
  seleteIdArr.value = value
  console.log(seleteIdArr.value)
}
//批量删除
const deleteSelectUser = async()=>{
  //整理批量删除参数
   let isList:any = seleteIdArr.value.map(item=>{
    return item.id
   })
  let result =  await reqDeleteAllUser(isList)
  if(result.code==200){
    ElMessage({
      type:'success',
      message:'批量删除成功'
    })
    getUserDataist()
  }else{
    ElMessage({
      type:'success',
      message:'批量删除失败'
    })
  }
}
//搜索按钮回调
const search =()=>{
  //根据关键字获取相应用户
  getUserDataist();
  //清空关键字
  keyword.value = ''
}
//
const reset = ()=>{
  settingStore.refsh = !settingStore.refsh
}
</script>

<style scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
